import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'MyDrawer.dart';
import '../api/Api.dart';
import '../util/NetUtils.dart';
import 'dart:convert';   //json解析在这个包中
import '../widgets/NewsDetailPage.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var listData;
  var titleList = new List<Map>();
  var bannerData;
  //拉取的最后时间
  var newsDate = "0";
  //拉取开关
  bool isLoad = true;
  var bodyWidget;
  var titleName = "今日热闻";
  ScrollController _controller = new ScrollController();
  TextStyle titleTextStyle = new TextStyle(fontSize: 15.0,fontWeight: FontWeight.w600);

  //获取数据的方法
  getNewData(){
      var url = Api.NEWS_LIST;
      NetUtils.get(url).then((data){
        if (data != null) {
          Map<String, dynamic> map = json.decode(data);
          
          var dataList = map['stories'];
          var bannerList = map['top_stories'];
          var date = map['date'];

          //根据时间再去拉取一天的数据
          bannerData = bannerList;
          newsDate = date;

          dataList.add({"timeTitle":getBeforeDateString(newsDate)});
          getTitleArray(dataList);
          getBeforeData(date,dataList: dataList);
        
        }
      });
  }

  //拉取之前数据
  getBeforeData(String date,{List dataList}){
    if (isLoad) {
         isLoad = false;
         var url = Api.NEWS_BEFORE + date;
          NetUtils.get(url).then((data){
              if (data != null) {
                Map<String, dynamic> map = json.decode(data);
                newsDate = map['date'];
                var newData = map['stories'];

                 //数据中拉取后添加标题
                newData.add({"timeTitle":getBeforeDateString(newsDate)});
                getTitleArray(newData);

                List datas = [];
                if (dataList != null) {
                  dataList.addAll(newData);
                  datas.addAll(dataList);
                }else{
                  datas.addAll(listData);
                  datas.addAll(newData);
                }
               
                isLoad = true;
                setState(() {
                  listData = datas;     
                });
              }
        });
    }
  }


   //处理数据计算title数组
  getTitleArray(List<dynamic> data){
    var totalH = 0.0;
    if (titleList.length > 0) {
      totalH += titleList[0]['height'];
    }else{
      totalH = 250;
    }
    data.forEach((content) {
      if (content['timeTitle'] != null) {
        totalH += 41;
        titleList.insert(0,{"title":content['timeTitle'],"height":totalH});
      } else {
        totalH += 91;
      }
    });
  }

   //根据时间字符串获取前一天的时间字符串 可以抽出去公共类用
  String getBeforeDateString(String nowDate) {
    if (nowDate.length != 8) {
      return "";
    }
    var beforDate = DateTime.parse(nowDate).add(Duration(days: -1)).toString();
    //把字符串中的-去掉
    var array = beforDate.split('-');
    return array[0] + array[1] + array[2].substring(0,2);
  }

  //处理数据把传入的时间字符串转成星期
  String exchangeTimeString(String timeString){
    var week = DateTime.parse(timeString).weekday;
    var weekStr;
    switch (week) {
      case 1:
        weekStr = '一';
        break;
      case 2:
        weekStr = '二';
        break;
      case 3:
        weekStr = '三';
        break;
      case 4:
        weekStr = '四';
        break;
      case 5:
        weekStr = '五';
        break;
      case 6:
        weekStr = '六';
        break;
      case 7:
        weekStr = '日';
        break;
    }

    // var year = timeString.substring(0,4);
    var month = timeString.substring(4,6);
    var day = timeString.substring(6,8);
    return "$month月$day日 星期$weekStr";
  }
  
  _HomePageState(){
    _controller.addListener((){
      var pixels = _controller.position.pixels;
      var maxScroll = _controller.position.maxScrollExtent;

      if (maxScroll - pixels <= 300) {
        getBeforeData(newsDate);
      }
    
      //便利List
      for (var i = 0; i < titleList.length; i++) {
           if (pixels >= titleList[i]["height"]) {
            if (titleName != exchangeTimeString(titleList[i]["title"])) {
                setState(() {
                  titleName = exchangeTimeString(titleList[i]["title"]);          
                });
            }
            break;
        }else{
            if (titleName != "今日热闻") {
                setState(() {
                  titleName = "今日热闻";          
                });
            }
        } 
      }

    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
      super.initState();
      getNewData();
    }

  @override
  Widget build(BuildContext context) {
    if (listData == null) {
      bodyWidget = new Center(
        child: new CircularProgressIndicator(),
      );
    } else {
      bodyWidget = new ListView.builder(
        itemCount: listData.length*2 + 1,
        itemBuilder: (context, i) => rederRow(i),
        controller: _controller,
      );
    }
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(titleName,
          style: new TextStyle(color: Colors.white)),
          iconTheme: new IconThemeData(color: Colors.white)
        ),
        body: bodyWidget,
        drawer: new MyDrawer()
      );
  }

   Widget rederRow(i) {
      if (i == 0) {
        return new Container(
            width: MediaQuery.of(context).size.width,
            height: 250.0,
            child: Swiper(
              itemBuilder: _swiperBuilder,
              itemCount: bannerData.length,
              pagination: new SwiperPagination(
                  builder: DotSwiperPaginationBuilder(
                color: Colors.black54,
                activeColor: Colors.white,
                space: 8,
                size: 6.0,
                activeSize: 6.0,
              )),
              scrollDirection: Axis.horizontal,
              autoplay: true,
              onTap: (index) => print('点击了第$index个'),
              )
          );
      }
    
      i -= 1;
      if (i.isOdd) {
        return new Padding(
          padding: const EdgeInsets.fromLTRB(15, 0, 0, 0),
          child: new Divider(height: 1.0),
        );
      }

      i = i ~/2;

      //创建时间的
      if (listData[i]['timeTitle'] != null) {
        return new Container(
          color: Colors.blue,
          height: 40,
          child: new Center(
            child: new Text(exchangeTimeString(listData[i]['timeTitle']),
              style: new TextStyle(
                color: Colors.white
              ),
            ),
          ),
        );
      }

      var titleRow = new Row(
        children: <Widget>[
          new Expanded(
            child: new Text(listData[i]['title'],style: titleTextStyle),
          )
        ],
      );
      var row = new Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          new Expanded(
            flex: 1,
            child: new Padding(
              padding: const EdgeInsets.all(15.0),
              child: new Column(
                children: <Widget>[
                  titleRow
                ],
              ),
            ),
          ),
          new Padding(
            padding: const EdgeInsets.all(15.0),
            child: new Container(
              width: 80,
              height: 60,
              color: Colors.grey[100],
              child: new Image.network(listData[i]['images'][0],fit: BoxFit.fill),
            ),
          )
        ],
      );

      return new InkWell(
        child: row,
        onTap: () {
          //点击跳转
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (ctx) => new NewsDetailPage(id:listData[i]['id'].toString())
            )
          );
        },
      );
    }
    
    //获取banner图片
    Widget _swiperBuilder(BuildContext context, int index) {
      return new Stack(
        children: <Widget>[
          Container(
            child: Image.network(
              bannerData[index]['image'],
              fit: BoxFit.fill,
              width: MediaQuery.of(context).size.width,
            ),
          ),
          Positioned(
            bottom: 0,
            child: DecoratedBox(
              decoration: BoxDecoration(
                gradient: LinearGradient(colors:[Colors.black45,Color.fromRGBO(1, 1, 1, 0)],begin: Alignment(0, 1.0),end: Alignment(0, -1.0))
              ),
              child: new Container(
                width: MediaQuery.of(context).size.width,
                height: 150,
              ),
            ),
          ),
          Positioned(
            bottom: 40,
            left: 15,
            right: 15,
            child: new Text(bannerData[index]['title'],style: TextStyle(color: Colors.white,fontSize: 19)),
          ),
        ],
      );
    }
}

